<template>
  <view>
    <!-- 图片组件（绑定所有API属性） -->
    <u--image
      :show-loading="showLoading"
      :src="currentSrc"
      :width="width"
      :height="height"
      :mode="mode"
      :shape="shape"
      :round="round"
      :lazy-load="lazyLoad"
      :show-menu-by-longpress="showMenuByLongpress"
      :loading-icon="loadingIcon"
      :error-icon="errorIcon"
      :show-error="showError"
      :fade="fade"
      :webp="webp"
      :duration="duration"
      :bg-color="bgColor"
      @click="handleClick"
      @error="handleImageError"
      @load="handleLoad"
    >
      <!-- 自定义加载中插槽 -->
      <template #loading v-if="showLoading">
        <slot name="loading">
          <!-- 默认加载图标 -->
          <u-icon :name="loadingIcon" size="36" color="#ccc"></u-icon>
        </slot>
      </template>

      <!-- 自定义错误插槽 -->
      <template #error v-if="showError">
        <view class="cover-error">
          <template v-if="defaultErrorImage">
            <image
              :src="defaultErrorImage"
              mode="widthFix"
              style="width: 60rpx; height: auto"
            ></image>
          </template>
          <template v-else>
            <u-icon :name="errorIcon" size="36" color="#ccc"></u-icon>
          </template>
          <view class="error-text">{{ errorText || "封面加载失败" }}</view>
        </view>
      </template>
    </u--image>
  </view>
</template>

<script setup>
import { ref, computed, watch } from "vue";
import { getResource } from "../../utils/Resource.js";
// 定义组件接收的所有APIProps
const props = defineProps({
  // 基础属性
  src: {
    type: String,
    required: true,
    default: "",
  },
  mode: {
    type: String,
    default: "widthFix",
    validator: (value) =>
      [
        "scaleToFill",
        "aspectFit",
        "aspectFill",
        "widthFix",
        "heightFix",
        "top",
        "bottom",
        "center",
        "left",
        "right",
        "top left",
        "top right",
        "bottom left",
        "bottom right",
      ].includes(value),
  },
  width: {
    type: [String, Number],
    default: "100vw",
  },
  height: {
    type: [String, Number],
    default: "auto",
  },

  // 形状与样式
  shape: {
    type: String,
    default: "square",
    validator: (value) => ["square", "circle"].includes(value), // 只允许square/circle
  },
  round: {
    type: [String, Number],
    default: 0,
  },
  bgColor: {
    type: String,
    default: "#f3f4f6",
  },

  // 加载相关
  lazyLoad: {
    type: Boolean,
    default: true,
  },
  showLoading: {
    type: Boolean,
    default: false,
  },
  showError: {
    type: Boolean,
    default: false,
  },
  loadingIcon: {
    type: String,
    default: "photo", // uView内置图标
  },
  errorIcon: {
    type: String,
    default: "error-circle", // uView内置图标
  },
  fade: {
    type: Boolean,
    default: false,
  },
  duration: {
    type: [String, Number],
    default: 500,
  },

  // 小程序特有
  showMenuByLongpress: {
    type: Boolean,
    default: true, // 仅微信小程序有效
  },
  webp: {
    type: Boolean,
    default: false, // 仅微信小程序有效
  },

  // 错误处理
  errorText: {
    type: String,
    default: "",
  },
  defaultErrorImage: {
    type: String,
    default: "",
  },
  fallbackSrc: {
    type: String,
    default: getResource("img/phone/logo.png"), // 默认备用图
  },
});
// 本地状态：管理当前显示的图片地址
const localSrc = ref(props.src);

// 监听props.src变化，同步到本地状态
watch(
  () => props.src,
  (newVal) => {
    localSrc.value = newVal;
  }
);

// 计算属性：最终显示的图片地址
const currentSrc = computed(() => {
  return localSrc.value || "/static/default-image.png";
});

// 事件处理
const emit = defineEmits(["click", "error", "load"]);

// 点击图片事件
const handleClick = () => {
  emit("click");
};

// 图片加载失败事件
const handleImageError = (err) => {
  // 切换到备用图
  localSrc.value = props.fallbackSrc;
  emit("error", err); // 传递错误信息
  console.log("图片加载失败：", err);
};

// 图片加载成功事件
const handleLoad = () => {
  emit("load"); // 触发load事件
};

// 图片预览（保持原有功能）
const previewImage = () => {
  if (currentSrc.value) {
    uni.previewImage({
      urls: [currentSrc.value],
      current: currentSrc.value,
    });
  }
};
</script>
<style lang="scss">
:deep(.u-image) {
  align-items: center !important;
  display: flex !important;
}
</style>
<style scoped lang="scss">
/* 基础错误样式 */
.cover-error {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  background-color: v-bind(bgColor); /* 绑定背景色 */
}
.error-text {
  margin-top: 8px;
  color: #999;
  font-size: 14px;
}

/* 根据shape和round动态设置样式 */
:deep(.u-image) {
  /* 形状处理：圆形 */
  &:not(.u-image--square) {
    border-radius: 50% !important;
  }
  /* 圆角处理（优先级低于shape） */
  border-radius: v-bind(round) !important;
}

/* 添加容器样式 */
:deep(.u-image) {
  image {
    width: 100%;
    height: auto !important;
  }

  /* 保持原有的形状处理 */
  &:not(.u-image--square) {
    border-radius: 50% !important;
  }
  border-radius: v-bind(round) !important;
}
</style>
